package blackstar.agent.web;

import java.io.File;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import blackstar.agent.AgentConfig;
import blackstar.agent.event.EventDispatcherSupport;
import blackstar.agent.event.EventListener;
import blackstar.agent.event.StartupEvent;

/**
 * @author RayWoo (ayufox@gmail.com)
 * 
 */
public class WebDeploy extends EventDispatcherSupport implements
		EventListener<StartupEvent>
{
	private final static Log LOGGER = LogFactory.getLog(WebDeploy.class);
	private final static String DEPLOY_PREFIX_KEY  = "web.deploy.";

	public Class[] events()
	{
		return new Class[]
		{ StartupEvent.class };
	}

	public void onEvent(StartupEvent event) throws Exception
	{
		LOGGER.info("init webapps");
		
		File webpath = new File(AgentConfig.getWebPath());
		if (!webpath.exists() || !webpath.isDirectory())
		{
			LOGGER.warn("webpath[" + webpath.getAbsolutePath()
					+ "] not exist or is not Directory");
		} else
		{
			File[] webs = webpath.listFiles();
			for (File web : webs)
			{
				if (web.isFile())
				{
					if (web.getName().endsWith(".war"))
					{
						String contextPath = "/" + web.getName().substring(0,
								web.getName().length() - 4);
						dispatch(new DeployWarEvent(web
								.getAbsolutePath(), contextPath));
					} else
					{
						LOGGER.warn("Illegal war [" + web.getAbsolutePath()
								+ "]");
					}
				} else
				{
					dispatch(new DeployWarEvent(web.getAbsolutePath(),
							"/" + web.getName()));
				}
			}
		}
		
		Properties properties = AgentConfig.getProperties();
		for (Map.Entry entry : properties.entrySet())
		{
			String key = (String) entry.getKey();
			if (key.startsWith(DEPLOY_PREFIX_KEY))
			{
				key = key.substring(DEPLOY_PREFIX_KEY.length());

				dispatch(new DeployWarEvent((String) entry.getValue(),
						"/" + key));
			}
			key = null;
		}
	}

}
